package com.atguigu.JUCAuxiliaryClass;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: CountDownLatchDemo
 * Package: com.atguigu.JUCAuxiliaryClass
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/29 20:18
 * version: 1.0
 */
public class CountDownLatchDemo {
    //案例：六个同学陆续离开教室，值班同学才可以离开教室

    public static void main(String[] args) throws InterruptedException {

        //创建倒数计数器对象
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{

                System.out.println(Thread.currentThread().getName()+"开始学习...");

                try {
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName()+"结束学习...离开教室");
                countDownLatch.countDown();


            },"同学"+i).start();

        }
        countDownLatch.await(10,TimeUnit.SECONDS);
        System.out.println(Thread.currentThread().getName()+"值班同学离开教室");
    }
}
